import sys
import json
import os
import uuid
import importlib

# 确保 subfolder 路径正确
sys.path.append(os.path.join(os.path.dirname(__file__), 'preview'))
sys.path.append(os.path.join(os.path.dirname(__file__), 'save'))

def execute_method(module_name, method_name, **kwargs):
    try:
        # 动态导入模块
        module = importlib.import_module(module_name)

        # 获取方法
        method = getattr(module, method_name)

        # 调用方法并返回结果
        result = method(**kwargs)
        return result
    except AttributeError:
        return f"Method {method_name} not found in module {module_name}"
    except ModuleNotFoundError:
        return f"Module {module_name} not found"
    except Exception as e:
        return str(e)

def read_json_data(file_path):
    with open(file_path, 'r', encoding='utf-8') as jsonfile:
        data = json.load(jsonfile)
    return data  # 返回原始数据结构，无需解析为键值对

def write_result_to_json(result):
    file_uuid = str(uuid.uuid4())
    output_file = f"{file_uuid}.json"
    with open(output_file, 'w') as jsonfile:
        json.dump(result, jsonfile)
    return os.path.abspath(output_file)

if __name__ == "__main__":
    arguments = sys.argv[1:]

    if len(arguments) < 3:
        print("Usage: python_script.py <module_name> <method_name> <json_file_path>")
        sys.exit(1)

    module_name = arguments[0]
    method_name = arguments[1]
    json_file_path = arguments[2]

    # 从 JSON 文件读取数据（不要求是键值对结构）
    json_data = read_json_data(json_file_path)

    # 将整个JSON数据作为参数传递给方法
    output = execute_method(module_name, method_name, data=json_data)

    # 将结果写入新的 JSON 文件并返回路径
    output_file_path = write_result_to_json(output)
    print(output_file_path)

    # 打印 sys.path 和模块文件路径以调试
    print(f"sys.path: {sys.path}")